<template>
  <div class="course-container">
    <div class="page-header">
      <h2>课程管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加课程
        </el-button>
        <!-- <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button> -->
      </div>
    </div>
    
    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.search"
            placeholder="课程名称或代码"
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.credits" placeholder="学分筛选" clearable>
            <el-option label="全部学分" value="" />
            <el-option label="1学分" :value="1" />
            <el-option label="2学分" :value="2" />
            <el-option label="3学分" :value="3" />
            <el-option label="4学分" :value="4" />
            <el-option label="5学分" :value="5" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 课程表格 -->
    <div class="course-table">
      <el-table
        :data="courseList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="code" label="课程代码" width="120" />
        <el-table-column prop="name" label="课程名称" width="200" />
        <el-table-column prop="credits" label="学分" width="80">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.credits }}分</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="课程描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createdTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.updatedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseFormRules"
        label-width="80px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input
            v-model="courseForm.name"
            placeholder="请输入课程名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="课程代码" prop="code">
          <el-input
            v-model="courseForm.code"
            placeholder="请输入课程代码"
            clearable
          />
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-select
            v-model="courseForm.credits"
            placeholder="请选择学分"
            style="width: 100%"
          >
            <el-option label="0.5学分" :value="0.5" />
            <el-option label="1学分" :value="1" />
            <el-option label="1.5学分" :value="1.5" />
            <el-option label="2学分" :value="2" />
            <el-option label="2.5学分" :value="2.5" />
            <el-option label="3学分" :value="3" />
            <el-option label="3.5学分" :value="3.5" />
            <el-option label="4学分" :value="4" />
            <el-option label="4.5学分" :value="4.5" />
            <el-option label="5学分" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Search,
  Refresh
} from '@element-plus/icons-vue'
import {
  getCoursePageApi,
  deleteCourseApi,
  createCourseApi,
  updateCourseApi
} from '@/api/course/course'

// 响应式数据
const loading = ref(false)
const courseList = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  credits: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0,
  hasPrev: false,
  hasNext: false
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const isEdit = ref(false)
const editId = ref(null)
const courseFormRef = ref()

// 课程表单
const courseForm = reactive({
  name: '',
  code: '',
  credits: '',
  description: ''
})

// 表单验证规则
const courseFormRules = {
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入课程代码', trigger: 'blur' }
  ],
  credits: [
    { required: true, message: '请选择学分', trigger: 'change' }
  ]
}

// 工具方法
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// API调用方法
const loadCourseList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }

    // 添加搜索条件
    if (searchForm.search) {
      params.search = searchForm.search
    }
    if (searchForm.credits) {
      params.credits = searchForm.credits
    }

    const response = await getCoursePageApi(params)

    if (response.code === 200) {
      courseList.value = response.data.data || []
      Object.assign(pagination, {
        currentPage: response.data.currentPage,
        pageSize: response.data.pageSize,
        totalCount: response.data.totalCount,
        totalPages: response.data.totalPages,
        hasPrev: response.data.hasPrev,
        hasNext: response.data.hasNext
      })
      ElMessage.success(`查询到 ${response.data.totalCount} 条课程记录`)
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadCourseList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    credits: ''
  })
  handleSearch()
}

const handleRefresh = () => {
  loadCourseList()
}

const handleAdd = () => {
  dialogTitle.value = '添加课程'
  isEdit.value = false
  Object.assign(courseForm, {
    name: '',
    code: '',
    credits: '',
    description: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑课程'
  isEdit.value = true
  editId.value = row.id
  Object.assign(courseForm, {
    name: row.name,
    code: row.code,
    credits: row.credits,
    description: row.description || ''
  })
  dialogVisible.value = true
}

const handleDialogClose = () => {
  dialogVisible.value = false
  courseFormRef.value?.resetFields()
}

const handleSubmit = async () => {
  try {
    await courseFormRef.value.validate()
    submitLoading.value = true

    let response
    if (isEdit.value) {
      const updateData = { ...courseForm, id: editId.value }
      response = await updateCourseApi(updateData)
    } else {
      response = await createCourseApi(courseForm)
    }

    if (response.code === 200) {
      ElMessage.success(response.message || `${isEdit.value ? '更新' : '添加'}成功`)
      handleDialogClose()
      loadCourseList()
    } else {
      ElMessage.error(response.message || `${isEdit.value ? '更新' : '添加'}失败`)
    }
  } catch (error) {
    console.error(`${isEdit.value ? '更新' : '添加'}课程失败:`, error)
    ElMessage.error(`${isEdit.value ? '更新' : '添加'}失败，请稍后重试`)
  } finally {
    submitLoading.value = false
  }
}

const handleImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

const handleExport = () => {
  ElMessage.info('导出数据功能开发中...')
}

const handleViewScores = (row) => {
  ElMessage.info(`查看成绩功能开发中... 课程：${row.name}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程 ${row.name}（${row.code}）吗？删除后相关的成绩记录也将被删除。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteCourseApi(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadCourseList() // 重新加载列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除课程失败')
    }
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadCourseList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadCourseList()
}

onMounted(() => {
  loadCourseList()
})
</script>

<style lang="scss" scoped>
.course-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }
  
  .course-table {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}



// 响应式设计
@media (max-width: 768px) {
  .course-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
      
      .header-actions {
        width: 100%;
        justify-content: flex-start;
      }
    }
    
    .search-section {
      .el-col {
        margin-bottom: 15px;
      }
    }
  }
}
</style>
